package com.example.sample.activity;

import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.ViewGroup;
import android.widget.ImageView;

import com.example.app.BaseActivity;

import me.everything.webp.WebPDecoder;

import net.liteheaven.xblib.common.ui.DimensionUtil;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * Created by LiangYu on 16/8/29
 */
public class WebpTestActivity extends BaseActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        try{
            init();
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    private void init() throws IOException {
        int length = DimensionUtil.dip2px(this, 100);
        ImageView imageView = new ImageView(this);
        imageView.setLayoutParams(new ViewGroup.LayoutParams(length, length));

        InputStream is = getAssets().open("720x1280.webp");
        Bitmap bitmap = WebPDecoder.getInstance().decodeWebP(streamToBytes(is));
        imageView.setImageBitmap(bitmap);
        setContentView(imageView);
    }

    private static byte[] streamToBytes(InputStream is) {
        ByteArrayOutputStream os = new ByteArrayOutputStream(1024);
        byte[] buffer = new byte[1024];
        int len;
        try {
            while ((len = is.read(buffer)) >= 0) {
                os.write(buffer, 0, len);
            }
        } catch (java.io.IOException e) {
        }
        return os.toByteArray();
    }
}
